﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using Win32;

namespace LibSpeedShot
{
	public class Capture
	{
		private bool _copyToClipboard = true;

		public bool CopyToClipboard 
		{
			get { return _copyToClipboard; }
			set { _copyToClipboard = value; }
		}

		public Capture()
		{

		}

		public Capture(bool copyToClipboard)
		{
			_copyToClipboard = copyToClipboard;
		}

		public bool CaptureWindow(string filePath)
		{
			Rectangle rect = ExternWindow.GetActiveWindowRect();
			return CaptureArea(filePath, rect);
		}

		public bool CaptureScreen(string filePath, bool captureTaskBar)
		{
			Rectangle rect;

			if (!captureTaskBar) { rect = Screen.PrimaryScreen.Bounds; }
			else { rect = Screen.PrimaryScreen.WorkingArea; }

			return CaptureArea(filePath, rect);
		}

		public bool CaptureRegion(string filePath, Color backColor, int opacity)
		{
			Rectangle rect = Screen.PrimaryScreen.Bounds;

			CaptureForm capForm = new CaptureForm();
			capForm.Size = rect.Size;
			capForm.TopMost = true;
			capForm.BackColor = backColor;
			capForm.Opacity = (double)opacity / 100.00d;
			capForm.ShowInTaskbar = false;

			capForm.ShowDialog();

			bool result = CaptureArea(filePath, capForm.SelectedRegion);
			capForm.Dispose();
			System.GC.Collect();

			return result;
		}

		private bool CaptureArea(string filePath, Rectangle rect)
		{
            if (rect.Width <= 0 || rect.Height <= 0) { return false; }

			Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);

			Graphics g = Graphics.FromImage(bmp);

			g.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size);

			bmp.Save(filePath, ImageFormat.Png);

			if (CopyToClipboard)
			{
				Clipboard.SetImage(bmp);
			}

            bmp.Dispose();
            g.Dispose();

			return true;
		}
	}
}
